package common;

import java.sql.Connection;
import java.sql.SQLException;

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

/**
 * @author jack
 * Connection pool implementation
 * singelton class uses mysql connector/J connection pool
 */
public class ConnectionPool 
{
	private MysqlDataSource dataSource = null;
	private static ConnectionPool instance = null;
	
	/**
	 * private singleton ctor, gets DB credentials
	 * @param serverUrl
	 * @param accountUser
	 * @param accountPassword
	 */
	private ConnectionPool(String serverUrl, String accountUser, String accountPassword)
	{
		dataSource = new MysqlDataSource();
		dataSource.setUrl(serverUrl);
		dataSource.setUser(accountUser);
		dataSource.setPassword(accountPassword);
	}
	
	/**
	 * @param serverUrl
	 * @param accountUser
	 * @param accountPassword
	 * @return the connection pool instance
	 */
	public static ConnectionPool CreateInstance(String serverUrl, String accountUser, String accountPassword) {

		if (instance == null) {
			synchronized(ConnectionPool.class) { 
				instance = new ConnectionPool(serverUrl, accountUser, accountPassword);
			}
		}
		return instance;
	}
	
	/**
	 * @return a connection from the connection pool
	 * @throws SQLException
	 */
	public static Connection GetConnection() throws SQLException
	{
		if (instance == null)
		{
			throw new IllegalStateException("Uninitialized pool");
		}
		
		synchronized( instance ){
			return instance.dataSource.getConnection();
		}
	}
}
